const Food = require("../models/food");
const FoodRecord = require("../models/foodRecord");

exports.add = async function (foodRecord) {
  return FoodRecord.create({
    ...foodRecord,
  });
};

exports.getRecord = async function (userId, recordDate) {
  // 查找指定日期不同时间段的打卡记录
  const breakfastRecord = await FoodRecord.findAll({
    where: { recordDate, userId, time: "早餐" },
    attributes: { exclude: ["updatedAt", "createdAt"] },
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
  });
  const lunchRecord = await FoodRecord.findAll({
    where: { recordDate, userId, time: "午餐" },
    attributes: { exclude: ["updatedAt", "createdAt"] },
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
  });
  const dinnerRecord = await FoodRecord.findAll({
    where: { recordDate, userId, time: "晚餐" },
    attributes: { exclude: ["updatedAt", "createdAt"] },
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
  });
  const addRecord = await FoodRecord.findAll({
    where: { recordDate, userId, time: "加餐" },
    attributes: { exclude: ["updatedAt", "createdAt"] },
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
  });
  let recordObj = {};
  if (breakfastRecord.length > 0) {
    recordObj.breakfast = breakfastRecord;
  }
  if (lunchRecord.length > 0) {
    recordObj.lunch = lunchRecord;
  }
  if (dinnerRecord.length > 0) {
    recordObj.dinner = dinnerRecord;
  }
  if (addRecord.length > 0) {
    recordObj.add = addRecord;
  }

  // 时间段映射
  let timeObj = {
    breakfast: "早餐",
    lunch: "午餐",
    dinner: "晚餐",
    add: "加餐",
  };

  let foodRecord = {}; // 存放最后返回的一天记录
  let recordKeys = Object.keys(recordObj);
  recordKeys.forEach((key) => {
    let tempObj = {},
      totalHeat = 0.0;
    tempObj.time = timeObj[key];
    tempObj.food = recordObj[key];
    // 计算一天某时间段的总摄入热量
    recordObj[key].forEach((item) => {
      totalHeat += item.heat;
    });
    tempObj.totalHeat = totalHeat;
    foodRecord[key] = tempObj;
  });

  // 初始化营养元素
  let nutritionData = [
    {
      name: "碳水化合物",
      weight: 0.0,
      percent: 0.0,
    },
    {
      name: "蛋白质",
      weight: 0.0,
      percent: 0.0,
    },
    {
      name: "脂肪",
      weight: 0.0,
      percent: 0.0,
    },
  ];

  let totalFoodRecord = [
    ...breakfastRecord,
    ...lunchRecord,
    ...dinnerRecord,
    ...addRecord,
  ];

  if (totalFoodRecord.length > 0) {
    totalFoodRecord.forEach((item) => {
      // 计算营养元素含量
      nutritionData[0].weight += item.carbohydrate;
      nutritionData[1].weight += item.protein;
      nutritionData[2].weight += item.fat;
    });
    // 计算占比
    let sum = 0;
    nutritionData.forEach((item) => {
      sum += item.weight;
    });
    nutritionData.forEach((item) => {
      item.percent = ((item.weight / sum) * 100).toFixed(2);
    });
    nutritionData[0].percent = (
      100 -
      nutritionData[1].percent -
      nutritionData[2].percent
    ).toFixed(2);
    nutritionData.forEach(item=>{
      item.weight = item.weight.toFixed(2);

  })
  }
  return {
    foodRecord,
    nutritionData,
  };
};

exports.remove = async function(id){
  return FoodRecord.destroy({
      where:{id},individualHooks:true
  })
},

exports.update = async function(foodRecord){
  const id = foodRecord.id;
  delete foodRecord.id;
  delete foodRecord.foodId,
  delete foodRecord.userId
  return FoodRecord.update(
      {...foodRecord}, 
      {where: {id: id}, individualHooks: true},
  )
}
